类型系统
相关界定/定义
类型定义
- 类型别名的声明(
type alias) - 接口声明(
interface) - 类声明(
class) - 枚举声明(
emum) - 指向类型的导入声明(
import)
值的定义
- 变量声明(
let,const,var声明) - 包含值的名称空间或者模块的声明(
namespace,module) - 枚举声明(
emun) - 类声明(
class) - 指向值的导入声明(
import) - 函数声明(
function)
类型分类
简单类型
- 类型字面量(数字,字符串)
objectstringnumberbooleanbigintsymbolFunctionnullundefinedunknownnevervoidanyX[]基础类型X的数组- [X,Y] 基础类型的元组
any任意类型
复合类型
- 对象类型(
object) - 联合类型(
union) - 类型别名(
type alias) - 接口类型(
interface) - 枚举类型(
enum) - 交集类型(
intersection) - 泛型(
generics)<Type> - 数组类型
Array<Type> - 只读数组
ReadOnlyArray<Type>
内置实用类型
Partial<Type>所有属性可选Required<Type>所有属性必选ReadOnly<Type>所有属性只读Record<Keys,Type>用Keys限制的key和用Type限制的value的对象类型Pick<Type,Keys>从Type中选择Keys中的字段作为key的对象Omit<Type,Keys>从Type中移除Keys中的字段剩下的作为字段作为属性的对象Exclude<Type,ExcludedUnion>从Type中排出不能赋值给ExcludedUnion剩下的Extract<Type,Union>从Type中取能赋值给Union的NonNullable<Type>排除null和undefinedParameters<Type>从函数Type参数中取ConstructorParameters<Type>从构造函数Type参数中获取ReturnType<Type>从函数Type返回值获取InstanceType<Type>从构造函数Type获取实例类型ThisParameterType<Type>取函数类型的this参数的类型,没有的话就用unknownOmitThisParameter<Type>从Type中删除this参数,没有就用Type,有就重新生成一个函数类型ThisType<Type>使用了noImplicitThis要打开,标注thisUppercase<StringType>Lowercase<StringType>Capitalize<StringType>Uncapitalize<StringType>
类型应用
函数中应用
参数中应用
可调用参数
Function函数类型表达式
(a: string) => boolean函数类型别名
type OneFunType = (a: string) => boolean调用签名(
call signatures)1
2
3
4
5
6
7type DescribableFunction = {
description: string;
(someArg: number): boolean;
};
function doSomething(fn: DescribableFunction) {
console.log(fn.description + " returned " + fn(6));
}构造签名(
construct signature)1
2
3
4
5
6
7
8
9
10
11type SomeConstructor = {
new (s: string): SomeObject;
};
function fn(ctor: SomeConstructor) {
return new ctor("hello");
}
interface CallOrConstruct {
new (s: string): Date;
(n?: number): number;
}泛型函数
1
2
3function firstElement<Type>(arr: Type[]): Type | undefined {
return arr[0];
}函数重载
this声明1
2
3interface DB {
filterUsers(filter: (this: User) => boolean): User[];
}
工厂方法中用
使用 new 关键字一起声明
1 | function create<Type>(c: { new (): Type }): Type { |
类中应用
代码组织
模块 module
导出 export
export let/const/var/interface/class/ XXexport {XX,YY}export {XX as YY} from 'in-module.ts'export default XXexport * as XX from 'in-module.ts'export = XX
导入 import
import {XX} from 'in-module.ts'import {XX as YY} from 'in-module.ts'import * as XX from 'in-module.ts'import 'in-module.ts'import type {XX} from 'in-module.ts'import XX = require('../in-module.ts')
名称空间 namespace
namespace XXX{} 可以实现
- 在模块内对模块进行逻辑分区
- 跨模块对名称空间内的内容进行合并
最后更新: 2022年03月02日 03:32
原始链接: http://rawbin-.github.io/language/2019-01-03-typescript-ref/